package com.srwl.mytx.camera2;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class CameraTouch {
    private float mOldScale = 1.0f;
    private float mScale;
    private float mSpan = 0;
    private float mOldSpan;
    private float mFirstDistance = 0;
    private CallBack callBack;

    public void onScale(MotionEvent event) {
        if (event.getPointerCount() == 2) {
            if (mFirstDistance == 0)
                mFirstDistance = distance(event);

            float distance = distance(event);
            float scale;
            if (distance > mFirstDistance) {
                scale = (distance - mFirstDistance) / 80;
                scale = scale + mSpan;
                mOldSpan = scale;
                mScale = scale;
            } else if (distance < mFirstDistance) {
                scale = distance / mFirstDistance;
                mOldSpan = scale;
                mScale = scale * mOldScale;
            } else {
                return;
            }

            if (callBack!=null){
                callBack.onScaleChange(mScale);
            }
            // mScaleSeekBar.setProgress((int) ((mScale / cameraHelper.getMaxZoom()) * mScaleSeekBar.getMax()));
            // if (mScale < 1.0f)
            //  mScaleSeekBar.setProgress(0);
        }
    }

    public void onScaleStart(MotionEvent event) {
        mFirstDistance = 0;
        // setScaleMax((int) cameraHelper.getMaxZoom());

        // mSeekBarLayout.setVisibility(View.VISIBLE);
        //removeSeekBarRunnable();
        Log.e("scale", "scale:start");
    }

    public void onScaleEnd(MotionEvent event) {
        if (mScale < 1.0f)
            mOldScale = 1.0f;
            //  else if (mScale > cameraHelper.getMaxZoom())
            //  mOldScale = cameraHelper.getMaxZoom();
        else
            mOldScale = mScale;
        mSpan = mOldSpan;

        if (event != null)
            // seekBarDelayedHind();
            Log.e("scale", "scale:end");
    }

    public void resetScale() {
        mOldScale = 1.0f;
        mSpan = 0f;
        mFirstDistance = 0f;
        //mScaleSeekBar.setProgress(0);
    }

    public void setScale(float scale) {
        mScale = scale;
        mOldSpan = scale;
        onScaleEnd(null);
    }

    /**
     * 计算两个手指间的距离
     *
     * @param event
     * @return
     */
    private float distance(MotionEvent event) {
        float dx = event.getX(1) - event.getX(0);
        float dy = event.getY(1) - event.getY(0);
        /** 使用勾股定理返回两点之间的距离 */
        return (float) Math.sqrt(dx * dx + dy * dy);
    }

    private void setScaleMax(int max) {
        //mScaleSeekBar.setMax(max * 100);
    }

    public void setCallBack(CallBack callBack) {
        this.callBack = callBack;
    }

    public interface CallBack {

        void onScaleChange(float scale);
    }
}



